define([
    'jquery',
    "layui",
    "signin",
    'jquery-cookie'
], function ($, layui, signin) {

    //修改用户地址
    function UserAddressTab() {
        //收货人修改
        $("#address_modify").click(function () {
            $(this).hide();
            $(".address_info").hide();
            $(".address_select").show();
        });

        $(".new_address").click(function () {
            $("form[name=address_form]").show();
            $(this).parent().addClass("cur").siblings().removeClass("cur");

        }).parent().siblings().find("input").click(function () {
            $("form[name=address_form]").hide();
            $(this).parent().addClass("cur").siblings().removeClass("cur");
        });

        //送货方式修改
        $("#delivery_modify").click(function () {
            $(this).hide();
            $(".delivery_info").hide();
            $(".delivery_select").show();
        })

        $("input[name=delivery]").click(function () {
            $(this).parent().parent().addClass("cur").siblings().removeClass("cur");
        });

        //支付方式修改
        $("#pay_modify").click(function () {
            $(this).hide();
            $(".pay_info").hide();
            $(".pay_select").show();
        })

        $("input[name=pay]").click(function () {
            $(this).parent().parent().addClass("cur").siblings().removeClass("cur");
        });

        //发票信息修改
        $("#receipt_modify").click(function () {
            $(this).hide();
            $(".receipt_info").hide();
            $(".receipt_select").show();
        })

        $(".company").click(function () {
            $(".company_input").removeAttr("disabled");
        });

        $(".personal").click(function () {
            $(".company_input").attr("disabled", "disabled");
        });
    }

    //加载用户购物车里的商品
    function getUserCartGoods() {
        let baseUrl = signin.getBaseUrl(); //获取基础地址
        let userInfo = null;
        let selectGoodsArr = null;
        let cartIds = [];
        signin.checkUserInfo() == null ? '' : userInfo = JSON.parse(signin.checkUserInfo()); //获取用户信息
        if (!userInfo) {
            location.href = 'login.html';
        }

        //商品数据
        if ($.cookie("selectGoods")) {
            //已选择商品
            selectGoodsArr = JSON.parse($.cookie("selectGoods")); //cookie中存贮的商品id,商品数量和购物车id

            let data = []; //商品id数组
            selectGoodsArr.forEach(item => {
                data.push(item.goodsId);
                cartIds.push(item.cartId);
            });

            $.post(baseUrl + "/goods/getGoodsByIds", {
                    goodsIds: data
                },
                function (res) {
                    // console.log(res);
                    let newGoodsArr = [];

                    let total = 0; //总价钱
                    let totalCount = 0; //总数量

                    //把商品数量放进返回的商品详情
                    for (let i = 0; i < selectGoodsArr.length; i++) {
                        for (let j = 0; j < res.data.length; j++) {
                            if (selectGoodsArr[i].goodsId == res.data[j].id) {
                                //获取cookie中商品的数量
                                res.data[j].goodsCount = selectGoodsArr[i].goodsCount;
                                newGoodsArr.push(res.data[j]);
                            }
                        }
                    }


                    //渲染选中的商品
                    newGoodsArr.forEach(item => {
                        let node = $(`
                        <tr data-cartId="${item.id}">
                                <td class="col1"><a href=""><img src="${item.goodsThumb}" alt="" /></a> <strong><a
                                            href="">${item.goodsName}</a></strong></td>
                                <td class="col2">
                                    <p>颜色：073深红</p>
                                    <p>尺码：170/92A/S</p>
                                </td>
                                <td class="col3">￥${item.shopPrice}</td>
                                <td class="col4"> ${item.goodsCount}</td>
                                <td class="col5"><span>￥${parseFloat(item.goodsCount * item.shopPrice).toFixed(2)}</span></td>
                            </tr>
                        `);
                        total += parseFloat(item.goodsCount * item.shopPrice);
                        totalCount += item.goodsCount;
                        $(".goods table").find("tbody").append(node);
                    });

                    //tfoot
                    let html = $(`
                     <tr>
                             <td colspan="5">
                                 <ul>
                                     <li>
                                         <span>${totalCount} 件商品，总商品金额：</span>
                                         <em>￥${total.toFixed(2)}</em>
                                     </li>                              
                                     <li>
                                         <span>应付总额：</span>
                                         <em>￥${total.toFixed(2)}</em>
                                     </li>
                                 </ul>
                             </td>
                         </tr>`);
                    $(".goods table").find("tfoot").append(html);
                    // 计算总金额
                    $('.fillin_ft strong').text('￥' + total.toFixed(2) + '元');

                });

        } else {
            //未选择商品
            $.get(baseUrl + "/cart/lists", {
                    userId: userInfo.id
                },
                function (res) {
                    // console.log(res);
                    let total = 0;
                    let totalCount = 0;
                    res.data.forEach(item => {

                        let node = $(`
                <tr data-cartId="${item.id}">
                        <td class="col1"><a href=""><img src="${item.goods.goodsThumb}" alt="" /></a> <strong><a
                                    href="">${item.goods.goodsName}</a></strong></td>
                        <td class="col2">
                            <p>颜色：073深红</p>
                            <p>尺码：170/92A/S</p>
                        </td>
                        <td class="col3">￥${item.goods.shopPrice}</td>
                        <td class="col4"> ${item.goodsCount}</td>
                        <td class="col5"><span>￥${parseFloat(item.goodsCount * item.goods.shopPrice).toFixed(2)}</span></td>
                    </tr>
                `);
                        total += parseFloat(item.goodsCount * item.goods.shopPrice);
                        totalCount += item.goodsCount;
                        $(".goods table").find("tbody").append(node);
                    });

                    //tfoot
                    let html = $(`
            <tr>
                    <td colspan="5">
                        <ul>
                            <li>
                                <span>${totalCount} 件商品，总商品金额：</span>
                                <em>￥${total.toFixed(2)}</em>
                            </li>                              
                            <li>
                                <span>应付总额：</span>
                                <em>￥${total.toFixed(2)}</em>
                            </li>
                        </ul>
                    </td>
                </tr>`);
                    $(".goods table").find("tfoot").append(html);
                    // 计算总金额
                    $('.fillin_ft strong').text('￥' + total.toFixed(2) + '元');
                });
        }

        // 获取到用户的地址库信息
        $.get(baseUrl + '/address/lists', {
            userId: userInfo.id
        }, function (res) {
            // console.log(res.data);

            res.data.forEach(function (item) {
                let node = $(`<li ${item.isDefault?"class='cur'":""} >
               <input type="radio" name="addressId" value="${item.id}" ${item.isDefault?"checked":""}>
               ${item.consignee} ${item.provinceName} ${item.cityName} ${item.areaName} ${item.address} ${item.mobile}
			    <a href="">编辑</a>
				<a href="">删除</a>
                </li>`);
                $('.address_select ul').append(node);
            });
            $(`<li><input type="radio" name="address" class="new_address"  />使用新地址</li>`);
        });

        console.log(cartIds);
        // 结算按钮 下单
        $('.fillin_ft a').on('click', function (res) {
            let data = $('.orderNow').serialize();
            // console.log(data);
            if (cartIds) {
                data += "&cartIds" + cartIds + '&userId=' + userInfo.id;
                console.log(data);
                $.post(baseUrl + '/order/orderNow', data,
                    function (res) {
                        if (res.code != 0) {
                            layer.msg(res.msg);
                            console.log(res);
                        } else {
                            location.href = 'success.html';
                            $.removeCookie("selectGoods"); //删除cooki中存贮的选中的商品
                        }
                    });
            } else {
                data += '&userId=' + userInfo.id;
                // console.log(data);
                $.post(baseUrl + '/order/orderNow', data, function (res) {
                    if (res.code != 0) {
                        layer.msg('暂无库存');
                    } else {
                        location.href = 'success.html';
                    }
                });
            }
            return false;
        });

    }


    return {
        UserAddressTab: UserAddressTab,
        getUserCartGoods: getUserCartGoods
    }

});